 import { Component, ElementRef, Input, OnInit, ViewChild, HostListener } from '@angular/core';
 import * as _ from 'lodash';
 import { FetchService } from '../../../../../core/net/fetch.service';
 import { concatMap } from 'rxjs/operators';
 import { FormBuilder, FormGroup } from "@angular/forms";
 import * as moment from "moment";
 import { format, startOfMonth, endOfMonth, subMonths, subDays } from 'date-fns';

 @Component({
    selector: 'app-statistical-chart',
    templateUrl: './statistical-chart-component.html',
    styleUrls: ['./statistical-chart-component.scss']
})
export class StatisticalChartComponent implements OnInit {
    @Input() manageId;
    echartsIntance: any;
    chartType = 0;
    channelList = [];
    historyForm: FormGroup;
    historyYearList = [];
    startHistoryValue: Date | null = null;
    endHistoryValue: Date | null = null;
    endHistoryOpen = false;
    historyOpt: any = {
        toolbox: {
            show: true,
            feature: {
                saveAsImage: {
                    show: true,
                    excludeComponents: ['toolbox'],
                    pixelRatio: 2,
                    name: '历史同期对比'
                }
            }
        },

        legend: {
            data: []
        },
        xAxis: {
            type: "category",
            data: []
        },
        yAxis: {
            type: "value"
        },
        series: []
    };
    historyOptChange: any = {};
    tableData = {};
    constructor(
        private fetchService: FetchService,
        private fb: FormBuilder
    ) {
        this.historyYearList = this.getLastSeveralYears();
        this.historyForm = this.fb.group({
            yearStr: [[moment().year()]],
            startDateStr: [moment().subtract(1, 'month').valueOf()],
            endDateStr: [new Date()],
            trId: [""],
        });

    }

    ngOnInit() {
        this.getChannelList();
    }

    onChartInit(e) {
        this.echartsIntance = e;
    }
    // 获取管理处对应渠道
    getChannelList() {
        const params = {
            "apicode": "33",
            "manageId": this.manageId
        };
        this.fetchService.post<any>('sys/sysApiInfo/queryApiData', params).subscribe(res => {
            if (Array.isArray(res) && res.length > 0) {
                this.channelList = res;
                this.historyForm.patchValue({ trId: this.channelList[0].id });
                this.onQueryHistory();
            } else {
                this.channelList = [];
            }
        });
    }

    private getLastSeveralYears(length = 10): Array<any> {
        const curYear = moment().year();
        const arr = [];
        for (let i = curYear - length; i <= curYear; i++) {
            arr.push(i);
        }
        return arr;
    }

    disabledHistoryStartDate = (startValue: Date): boolean => {
        if (!startValue || !this.endHistoryValue) {
            return false;
        }
        return startValue.getTime() > this.endHistoryValue.getTime();
    }

    disabledHistoryEndDate = (endValue: Date): boolean => {
        if (!endValue || !this.startHistoryValue) {
            return false;
        }
        return endValue.getTime() <= this.startHistoryValue.getTime();
    }

    onStartHistoryChange(date: Date): void {
        this.startHistoryValue = date;
    }

    onEndHistoryChange(date: Date): void {
        this.endHistoryValue = date;
    }
    handleStartHistoryOpenChange(open: boolean): void {
        if (!open) {
            this.endHistoryOpen = true;
        }
    }

    handleEndHistoryOpenChange(open: boolean): void {
        this.endHistoryOpen = open;
    }

    onQueryHistory(): void {
        if (this.historyForm.value.trId
            && this.historyForm.value.yearStr.length > 0
            && this.historyForm.value.startDateStr
            && this.historyForm.value.endDateStr) {
            this.historyOpt.series = [];
            const params = {
                trId: this.historyForm.value.trId,
                startDateStr: moment(this.historyForm.value.startDateStr).format('MM-DD'),
                endDateStr: moment(this.historyForm.value.endDateStr).format('MM-DD'),
                yearStr: this.historyForm.value.yearStr.join(','),
                valType: "2", // 流量
            };
            this.fetchService.post('report/muwWf/historySameTimeCampare', params).subscribe(res => {
                if (res && Array.isArray(res)) {
                    this.historyOpt.series = [];
                    this.historyOpt.legend = [];
                    if (this.echartsIntance) {
                        this.echartsIntance.clear();
                    }
                    this.historyOptChange = {
                        tooltip: {
                            trigger: "axis",
                            axisPointer: {
                                type: "shadow"
                            }
                        },
                        legend: {
                            data: res.map(o => {
                                return o.year;
                            })
                        },
                        xAxis: {
                            data: res[0].data.map(o => {
                                return moment(o.time).format("MM-DD HH:mm:ss");
                            })
                        },
                        yAxis: {
                            name: this.historyForm.value.valType === '1' ? '水位（m）' : '流量（m³/s）'
                        },
                        series: res.map(o => {
                            return {
                                name: o.year,
                                type: "line",
                                smooth: true,
                                data: o.data.map(item => {
                                    return item.val;
                                })
                            };
                        })
                    };
                    this.getTableData(res);
                }
            });
        }
    }

    changeChartType() {
        this.chartType = this.chartType ? 0 : 1;
    }

    getTableData(res) {
        const tableData = {};
        this.historyOptChange.xAxis.data.forEach(time => {
            tableData[time] = [];
        });
        res.forEach(yearObj => {
            const arrcache = [];
            yearObj.data.forEach(dayObj => {
                const key = moment(dayObj.time).format("MM-DD HH:mm:ss");
                tableData[key].push(dayObj.val);
            });
        });
        this.tableData = _.cloneDeep(tableData);
    }

}
